package com.hopu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hopu.service.OSSService;
import com.hopu.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.hopu.exception.BusinessException;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OSSServiceImpl implements OSSService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    @Autowired
     StaffService staffServic;

    //上传文件
    @Override
    public String uploadFile(MultipartFile file) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件名
            String fileName = file.getOriginalFilename();
            //截取文件格式
            final String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            //重新生成文件名
            String name = UUID.randomUUID() + "." + fileType;
            // 上传文件到指定的存储桶
            ossClient.putObject(bucketName, name, inputStream);
            // 关闭文件流
            inputStream.close();
            // 返回文件的URL地址
            return urlPrefix + name;
        } catch (Exception e) {
            throw new BusinessException("上传失败！请联系管理员");
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

}
